from flask import render_template, url_for, flash, redirect, get_flashed_messages, request
from flask_login import current_user, login_user, logout_user, login_required  # 10.18
from werkzeug.urls import url_parse
from app import app, db

from app.forms import LoginForm, RegistrationForm
from app.models import User  # 10.18  引User模型

@app.route('/')
@app.route('/index')
@login_required
def index():
    user = {'username':'张老三'}
    posts = [
        {
            'author': {'username': '毛泽东'},
            'body': '这是模版模块中循环例子1-毛泽东思想'
        },
        {
            'author': {'username': '习近平'},
            'body': '这是模版模块中循环例子2-二十大召开'
        }
    ]
    
    return render_template('index.html',  title='我的', user=current_user, posts=posts)

@app.route('/login', methods=['GET', 'POST'])
def login():
    #判断当前用户是否验证，如果通过的话返回首页
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    form = LoginForm()
    if form.validate_on_submit():
        # flash(f'用户的登录名是：{form.username.data}, 是否记住我：{form.remember_me.data}')
        # return redirect(url_for('index'))
        user = User.query.filter_by(username=form.username.data).first()

        # 验证用户是否存在，或密码是否正确
        if user is None or not user.check_password(form.password.data):
            flash('无效用户名和密码')
            return redirect(url_for('login'))

        login_user(user, remember=form.remember_me.data)

        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')

        return redirect(next_page)

    return render_template('login.html', title='登录', form=form)

@app.route('/register', methods=['GET', 'POST'])
def register():
    # 判断当前用户是否验证，如果通过的话返回首页
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('恭喜你成为我们网站的新用户!')
        return redirect(url_for('login'))
    return render_template('register.html', title='注册', form=form)


@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))